package biz.inspeed.test.mina;

/**
 * @author Himi
 */

import java.util.concurrent.TimeUnit;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

public class MinaClientHanlder extends IoHandlerAdapter {

	@Override
	public void sessionCreated(IoSession session) throws Exception {
		System.out.println("sessionCreated");
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {

		String getJsonString = "{'topKey':'0100','objs':null,'mark':'ed3d6dfb-18be-4c17-8e42-e7c2d07fab6b'}";
		System.out.println("sessionOpened" + getJsonString);
		new Thread(new Annoyer(session)).start();
	}

	@Override
	public void sessionClosed(IoSession session) {
		System.out.println("I'm Client &&  I closed!");
	}

	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {

		System.out.println(message);

	}
	
	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		super.exceptionCaught(session, cause);
		 flag = false;
	}

	boolean flag = true;
	class Annoyer implements Runnable {
		IoSession session;
		Annoyer(IoSession session){
			this.session = session;
		}
		@Override
		public void run() {
			int index = 0;
			while(flag){
				String str = "annoyer says: " + index ++;
				session.write( str);
				System.out.println(str);
				try {
					TimeUnit.SECONDS.sleep(5);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			System.out.println("DONE!");
		}
	}
}
